package cn.dyw.engine.core.order;

import cn.dyw.engine.core.Constants;
import cn.dyw.engine.core.context.ReportStandardContext;
import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLOrderBy;
import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 默认的 排序渲染
 *
 * @author dyw770
 * @since 2021-08-09
 */
@Slf4j
public class DefaultSortRender implements ISortRender {

    @Override
    public String sortRender(String sql, ReportStandardContext context) {
        List<ExecSort> sorts = context.getSorts();
        return sortRender(sql, sorts, context);
    }

    public String sortRender(String sql, List<ExecSort> sorts, ReportStandardContext context) {

        if (sorts.isEmpty()) {
            return sql;
        }

        DbType dbType = context.getDbType();

        SQLSelectStatement stmt = (SQLSelectStatement) SQLUtils.parseSingleStatement(sql, dbType);

        SQLSelectQueryBlock sqb = new SQLSelectQueryBlock(dbType);
        sqb.setFrom(stmt.getSelect(), Constants.TMP_ORDER_SQL_AlIAS);

        SQLOrderBy orderBy = new SQLOrderBy();

        for (int i = 0; i < sorts.size(); i++) {
            ExecSort execSort = sorts.get(i);
            orderBy.addItem(SQLUtils.toOrderByItem(execSort.getFieldName() + " " + execSort.getOrderType(), dbType));
        }

        sqb.setOrderBy(orderBy);

        sqb.addSelectItem(SQLUtils.toSelectItem("*", dbType));

        String orderSql = SQLUtils.toSQLString(sqb, dbType);
        log.debug("渲染的排序SQL： {}", orderSql);

        return orderSql;
    }
}
